package com.os.core.service.field.impl;

import com.os.common.annotation.ds.DynamicDatasource;
import com.os.common.entity.field.FieldAdd;
import com.os.common.entity.field.FieldAlter;
import com.os.common.entity.field.FieldDelete;
import com.os.common.utils.MyUtil;
import com.os.core.mapper.FieldMapper;
import com.os.core.service.field.FieldService;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 描述：字段服务实现类
 *
 * @author huxuehao
 **/
@Service
public class FieldServiceImpl implements FieldService {
    private final FieldMapper fieldMapper;

    public FieldServiceImpl(FieldMapper fieldMapper) {
        this.fieldMapper = fieldMapper;
    }

    /**
     * 新增表字段
     * @param fieldAdd 参数实体
     */
    @Override
    @DynamicDatasource
    public List<String> filedBatchAdd(String datasourceId, FieldAdd fieldAdd) {
        String option,exists;
        List<String> list = new LinkedList<>();
        for (String tableName : fieldAdd.getTableNames()) {
            StringBuilder add = new StringBuilder();
            if (fieldAdd.getIsCover()) {
                exists = "EXISTS";
                option = "MODIFY";
            } else {
                exists = "NOT EXISTS";
                option = "ADD";
            }
            add.append("IF ").append(exists).append(" ( SELECT 1 FROM information_schema.columns WHERE table_schema = (SELECT DATABASE()) AND table_name = '")
                    .append(tableName)
                    .append("' AND column_name = '")
                    .append(fieldAdd.getFieldName())
                    .append("' )\n")
                    .append("ALTER TABLE `")
                    .append(tableName)
                    .append("` ").append(option).append("` ")
                    .append(fieldAdd.getFieldName())
                    .append("` ")
                    .append(fieldAdd.getFieldType());
            if (fieldAdd.getFieldIsNull()) {
                add.append(" DEFAULT NULL ");
            } else {
                add.append(" NOT NULL ");
            }
            add.append("COMMENT '").append(fieldAdd.getFieldComment()).append("';\n");
            list.add(add.toString());
        }
        return list;
    }

    /**
     * 删除表字段
     * @param fieldDelete 参数实体
     */
    @Override
    @DynamicDatasource
    public List<String> filedBatchDelete(String datasourceId, FieldDelete fieldDelete) {
        List<String> columnNames = fieldMapper.regexField(fieldDelete);
        List<String> list = new LinkedList<>();
        for (String tableName : fieldDelete.getTableNames()) {
            for (String columnName : columnNames) {
                list.add("ALTER TABLE " + tableName + " DROP COLUMN `" + columnName + "`;");
            }
        }
        return list;
    }

    /**
     * 修改表字段
     * @param fieldAlter 参数实体
     */
    @Override
    @DynamicDatasource
    public  List<String> filedBatchAlter(String datasourceId, FieldAlter fieldAlter) {
        List<Map<String, String>> sqlRes = fieldMapper.regexMatch(fieldAlter);
        if (MyUtil.isEmpty(sqlRes)){
            return null;
        }
        String newFieldName = fieldAlter.getNewFieldName();
        String newFieldType = fieldAlter.getNewFieldType();
        String newFieldLength = fieldAlter.getNewFieldLength();
        String newFieldComment = fieldAlter.getNewFieldComment();
        Boolean delete = fieldAlter.getDelete();
        List<String> list = new LinkedList<>();
        for (Map<String, String> map : sqlRes) {
            String tableName = map.get("TABLE_NAME");
            StringBuilder builder = new StringBuilder();
            if (delete) {
                list.add("ALTER TABLE `" + tableName + " DROP " + map.get("COLUMN_NAME") + ";");
                builder.append("ALTER TABLE `").append(tableName).append("` ADD COLUMN ");
            } else {
                builder.append("ALTER TABLE `").append(tableName).append("` MODIFY COLUMN ");
            }
            if (MyUtil.isEmpty(newFieldName)) {
                builder.append("`").append(map.get("COLUMN_NAME")).append("` ");
            } else {
                builder.append("`").append(newFieldName).append("` ");
            }
            if (MyUtil.isEmpty(newFieldType)) {
                builder.append(map.get("DATA_TYPE")).append(" ");
            } else {
                builder.append(newFieldType);
                if (!MyUtil.isEmpty(newFieldLength) && Integer.parseInt(newFieldLength) > 0){
                    builder.append("(").append(newFieldLength).append(")").append(" ");
                } else {
                    builder.append(" ");
                }
            }
            if (MyUtil.isEmpty(newFieldComment)){
                builder.append("COMMENT").append(" '").append(map.get("COLUMN_COMMENT")).append("';");
            } else {
                builder.append("COMMENT").append(" '").append(newFieldComment).append("';");
            }
            list.add(builder.toString());
        }
        return list;
    }
}
